package com.caszx.chargingpile.fragment.station;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONException;
import com.app.base.fragment.BaseNetViewFragment;
import com.app.jsonparse.JSONParse;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.activity.CityActivity;
import com.caszx.chargingpile.activity.MainActivity;
import com.caszx.chargingpile.activity.ReservatePayActivity;
import com.caszx.chargingpile.activity.StationDetailActivity;
import com.caszx.chargingpile.activity.StationListActivity;
import com.caszx.chargingpile.entity.EntityCity;
import com.caszx.chargingpile.entity.EntityStation;
import com.caszx.chargingpile.eventbus.EventBusAction;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.user.LocationManager;
import com.caszx.chargingpile.utils.DialogHelp;
import com.jakewharton.rxbinding.view.RxView;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import de.greenrobot.event.EventBus;
import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;
import rx.functions.Action1;


/**
 * 电站首页
 */
public class StationHomeFragment extends BaseNetViewFragment implements View.OnClickListener, BaiduMap.OnMarkerClickListener, BaiduMap.OnMapClickListener {


    private Toolbar mToolbar;
    private TextView mTxtTopLeft;
    private TextView mBtn_nai;
    private MapView mMapView = null;
    private BaiduMap mBaiduMap;

    private FrameLayout map;

    private Marker mPreSelecteMarker;
    private Marker mCurrentMarker;
    private List<EntityStation> mStations;
    //电站面板
    private LinearLayout layoutPaner;
    private TextView btn_reservate;
    private TextView txt_station_address;
    private TextView txt_station_distance;
    private TextView txt_station_available;

    private TextView txt_beforeFee;
    private TextView txt_stopcarFee;
    private TextView txt_serverFeeAc;

    //三种图标
    private BitmapDescriptor mBitmapSpot = BitmapDescriptorFactory.fromResource(R.mipmap.map_spot);
    private BitmapDescriptor mBitmapCurrent = BitmapDescriptorFactory.fromResource(R.mipmap.map_current);
    private BitmapDescriptor mBitmapSelecte = BitmapDescriptorFactory.fromResource(R.mipmap.map_selected);

    public static StationHomeFragment newInstance() {
        StationHomeFragment fragment = new StationHomeFragment();
        return fragment;
    }

    @Override
    protected void onLoad() {
        String city = LocationManager.getInstance().getCityName();
        if (TextUtils.isEmpty(city)) {
            EventBus.getDefault().post(EventBusAction.ACTION_REQUEST_LOCATION);
        } else {
            getStationList(city);
        }
    }

    /**
     * 定位的回调
     */
    public void onEvent(String action) {
        if (EventBusAction.ACTION_REQUEST_LOCATION_SU.equals(action)) {
            //定位成功
            String city = LocationManager.getInstance().getCityName();
            if (!TextUtils.isEmpty(city)) {
                getStationList(city);
            }
        } else if (EventBusAction.ACTION_REQUEST_LOCATION_ER.equals(action)) {
            //定位失败
            showErrorView("定位失败");
        }
    }

    /**
     * 点击城市列表
     */
    public void onEvent(EntityCity action) {
        showProgressDialog("");
        LocationManager.getInstance().setCityName(action.city);
        LocationManager.getInstance().setLatitude(action.latitude);
        LocationManager.getInstance().setLongitude(action.longitude);
        mTxtTopLeft.setText(action.city.replace("市", ""));
        getStationList(action.city);
    }

    @Override
    protected View initOnloadedView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_station_home, null);
        initToolbar(view);
        initPanner(view);
        initInfoView(view);
        initBaiduMap(view);
        return view;
    }

    private void initPanner(View view) {
        layoutPaner = (LinearLayout) view.findViewById(R.id.layoutPaner);
        btn_reservate = (TextView) view.findViewById(R.id.btn_reservate);
        txt_station_address = (TextView) view.findViewById(R.id.txt_station_address);
        txt_station_available = (TextView) view.findViewById(R.id.txt_station_available);
        txt_station_distance = (TextView) view.findViewById(R.id.txt_station_distance);

        txt_beforeFee = (TextView) view.findViewById(R.id.txt_beforeFee);
        txt_stopcarFee = (TextView) view.findViewById(R.id.txt_stopcarFee);
        txt_serverFeeAc = (TextView) view.findViewById(R.id.txt_serverFeeAc);
        RxView.clicks(txt_station_address).throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        int position = mPreSelecteMarker.getExtraInfo().getInt("ID");
                        Intent intent = new Intent(getActivity(), StationDetailActivity.class);
                        intent.putExtra("ID", mStations.get(position).stationId);
                        startActivity(intent);
                    }
                });
        RxView.clicks(btn_reservate).throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        int position = mPreSelecteMarker.getExtraInfo().getInt("ID");
                        Intent intent = new Intent(getActivity(), ReservatePayActivity.class);
                        intent.putExtra("ID", mStations.get(position).stationId);
                        intent.putExtra("NAME", mStations.get(position).name);
                        getActivity().startActivity(intent);
                    }
                });

    }

    private void getStationList(String city) {
        cancelAll(this);
        HashMap<String, String> params = new HashMap<>();
        params.put("city", city == null ? "" : city);
        params.put("latitude", LocationManager.getInstance().getLatitude() + "");
        params.put("longitude", LocationManager.getInstance().getLongitude() + "");
        //params.put("plieType","合肥");
        //params.put("stationName","合肥");
        OkHttpUtils.post()
                .url(ConstantUrl.URL_STATION_LIST)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        showErrorView(R.string.error_network);
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"),null);
                                showErrorView(resultJsonObject.optString("msg"));
                            } else {
                                try {
                                    mStations = JSONParse.parseArray(response.optString("data"), EntityStation.class);
                                    showContentView();
                                    showMark(mStations);
                                    String city = LocationManager.getInstance().getCityName();
                                    mTxtTopLeft.setText(city.replace("市", ""));
                                    LatLng point = new LatLng(LocationManager.getInstance().getUserLatitude(), LocationManager.getInstance().getUserLongitude());
                                    OverlayOptions option = new MarkerOptions()
                                            .position(point)
                                            .icon(mBitmapCurrent)
                                            .animateType(MarkerOptions.MarkerAnimateType.grow);
                                    mCurrentMarker = (Marker) mBaiduMap.addOverlay(option);
                                    mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));
                                } catch (JSONException e) {
                                    showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }

    private void initInfoView(View view) {
        mBtn_nai = (TextView) view.findViewById(R.id.btn_nai);
        mBtn_nai.setOnClickListener(this);
    }

    /**
     * @author 闫鹏飞
     * @time 2018-11-21 0021  16:42
     * @describe 初始化工具栏
     */
    private void initToolbar(View view) {
        mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        mTxtTopLeft = (TextView) view.findViewById(R.id.txtTopLeft);
        mToolbar.inflateMenu(R.menu.menu_station_hamburger);
        //工具栏右侧按钮
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Intent intent = new Intent(getActivity(), StationListActivity.class);
                if (mStations != null) {
                    intent.putParcelableArrayListExtra("STATION", (ArrayList<? extends Parcelable>) mStations);
                }
                ((MainActivity) getActivity()).startActivity(intent, false);
                getActivity().overridePendingTransition(R.anim.activity_push_right_in, R.anim.activity_right_out);
                return true;
            }
        });
        //工具栏左侧按钮
        mTxtTopLeft.setText("城市");
        RxView.clicks(mTxtTopLeft).throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        Intent intent = new Intent(getActivity(), CityActivity.class);
                        getActivity().startActivity(intent);
                    }
                });
    }

    private void initBaiduMap(View view) {
        map = (FrameLayout) view.findViewById(R.id.map);
        BaiduMapOptions baiduMapOptions = new BaiduMapOptions();
        baiduMapOptions.compassEnabled(true);
        baiduMapOptions.zoomControlsEnabled(false);
        mMapView = new MapView(getActivity(), baiduMapOptions);
        map.addView(mMapView);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(13));
        mBaiduMap.setTrafficEnabled(true);
        mBaiduMap.setOnMarkerClickListener(this);
        mBaiduMap.setOnMapClickListener(this);
        UiSettings uiSettings = mBaiduMap.getUiSettings();
        uiSettings.setAllGesturesEnabled(true);
        uiSettings.setCompassEnabled(true);
        uiSettings.setZoomGesturesEnabled(true);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mMapView != null) {
            mMapView.setVisibility(View.VISIBLE);
            mMapView.onResume();
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if (mMapView != null) {
            mMapView.setVisibility(View.INVISIBLE);
            mMapView.onPause();
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
        if (mMapView != null)
            mMapView.onDestroy();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker == mCurrentMarker) return true;
        if (mPreSelecteMarker != null) {
            mPreSelecteMarker.setIcon(mBitmapSpot);
        }
        mPreSelecteMarker = marker;
        marker.setIcon(mBitmapSelecte);

        int position = marker.getExtraInfo().getInt("ID");
        if (isDown) {
            translateViewUp(layoutPaner);
        }
        refrashPanner(position);
        return true;
    }


    private static DecimalFormat format = new DecimalFormat("##.##");

    private void refrashPanner(int position) {
        if (position < 0) {
            translateViewDown(layoutPaner);
        } else {
            EntityStation station = mStations.get(position);
            txt_station_address.setText(station.address);
            txt_station_available.setText(station.fastRuningPile + "个电桩可用");
            txt_station_distance.setText(format.format(station.distence / 1000) + "Km");
            txt_beforeFee.setText("充电费" + format.format(station.priceDc) + "元/度");
            txt_stopcarFee.setText("停车费" + format.format(station.stopcarFee) + "元/小时");
            txt_serverFeeAc.setText("服务费" + format.format(station.serverFeeAc) + "元/次");
        }
    }

    private void showMark(List<EntityStation> stations) {
        mBaiduMap.clear();
        if (stations == null || stations.size() == 0) {
            refrashPanner(-1);
            return;
        }
        for (int i = 0, len = stations.size(); i < len; i++) {
            EntityStation station = stations.get(i);
            Bundle bundle = new Bundle();
            bundle.putInt("ID", i);
            LatLng point = new LatLng(Double.parseDouble(station.latitude), Double.parseDouble(station.longitude));
            OverlayOptions option = new MarkerOptions()
                    .position(point)
                    .icon(mBitmapSpot)
                    .animateType(MarkerOptions.MarkerAnimateType.grow)
                    .extraInfo(bundle);
            if (i == 0) {
                mPreSelecteMarker = (Marker) mBaiduMap.addOverlay(option);
                mPreSelecteMarker.setIcon(mBitmapSelecte);
                if (isDown) {
                    translateViewUp(layoutPaner);
                }
                refrashPanner(0);
            } else {
                mBaiduMap.addOverlay(option);
            }
        }
    }

//    private static LatLng point1 = new LatLng(31.838432,117.152682);
//    private static LatLng point2 = new LatLng(31.838432,117.252682);
//    private static LatLng point3 = new LatLng(31.888432,117.155682);
//    private static LatLng point4 = new LatLng(31.858432,117.182682);
//    private static LatLng point5 = new LatLng(31.838432,117.192682);
//    private static LatLng point6 = new LatLng(31.898432,117.102682);
//    private static LatLng point7 = new LatLng(31.028432,117.002682);

    @Override
    public void onMapClick(LatLng latLng) {
        if (mPreSelecteMarker != null) {
            mPreSelecteMarker.setIcon(mBitmapSpot);
            mPreSelecteMarker = null;
        }

        if (mStations != null && mStations.size() != 0) {
            translateViewDown(layoutPaner);
        }
    }

    @Override
    public boolean onMapPoiClick(MapPoi mapPoi) {
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //导航
            case R.id.btn_nai:
                if (mPreSelecteMarker == null) {
                    DialogHelp.showDialogOnlyMesg(getActivity(), "请选择一个电站", null);
                    return;
                }
                if (BaiduNaviManager.isNaviInited() && mCurrentMarker != null) {
                    double start_longitude = mCurrentMarker.getPosition().longitude;
                    double start_latitude = mCurrentMarker.getPosition().latitude;
                    String start_title = mCurrentMarker.getTitle();
                    double end_longitude = mPreSelecteMarker.getPosition().longitude;
                    double end_latitude = mPreSelecteMarker.getPosition().latitude;
                    String end_title = mPreSelecteMarker.getTitle();
                    LocationManager.getInstance().routeplanToNavi(getActivity(), start_longitude, start_latitude, start_title, end_longitude, end_latitude, end_title);
                }
                break;
        }
    }


    private boolean isDown = true;

    private void translateViewDown(View view) {
        if (isDown) return;
        isDown = true;
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, View.TRANSLATION_Y, 0, view.getHeight()).setDuration(300);
        objectAnimator.start();
    }

    private void translateViewUp(View view) {
        isDown = false;
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, View.TRANSLATION_Y, view.getHeight(), 0)
                .setDuration(300);
        objectAnimator.start();
    }
}
